package com.atguigu.gmallrealtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.atguigu.gmallrealtime.bean.TrafficPageViewBean;
import com.atguigu.gmallrealtime.common.Constant;
import com.atguigu.gmallrealtime.util.DateFormatUtil;
import com.atguigu.gmallrealtime.util.DorisUtil;
import com.atguigu.gmallrealtime.util.MyKafkaUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple4;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

/**
 * @author yhm
 * @create 2023-10-09 9:21
 */
public class DwsTrafficVcChArIsNewPageViewWindow {
    public static void main(String[] args) throws Exception {
        // TODO 1 创建flink环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        // TODO 2 添加检查点和状态后端
        env.enableCheckpointing(3000L, CheckpointingMode.EXACTLY_ONCE);

        //2.2 设置检查点超时时间
        env.getCheckpointConfig().setCheckpointTimeout(60000L);
        //2.3 设置job取消之后 检查点是否保留
        env.getCheckpointConfig().setExternalizedCheckpointCleanup(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
        //2.4 设置两个检查点之间最小的时间间隔
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(2000L);
        //2.5 设置重启策略
        // env.setRestartStrategy(RestartStrategies.fixedDelayRestart(3,3000L));
        env.setRestartStrategy(RestartStrategies.failureRateRestart(3, Time.days(30), Time.seconds(3)));

        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");

        System.setProperty("HADOOP_USER_NAME","atguigu");

        // TODO 3 读取dwd_traffic_page主题数据
        String groupId = "dws_traffic_vc_ch_ar_is_new_page_view_window";
        KafkaSource<String> kafkaSource = MyKafkaUtil.getKafkaSource(Constant.TOPIC_DWD_TRAFFIC_PAGE, groupId);
        DataStreamSource<String> pageSource = env.fromSource(kafkaSource, WatermarkStrategy.noWatermarks(), "page_source");

//        pageSource.print();

        // TODO 4 判断是否为独立访客 -> 根据mid进行分组
        KeyedStream<JSONObject, String> keyedStream = pageSource.map(new MapFunction<String, JSONObject>() {
            @Override
            public JSONObject map(String value) throws Exception {
                return JSON.parseObject(value);
            }
        })
                .keyBy(new KeySelector<JSONObject, String>() {
                    @Override
                    public String getKey(JSONObject value) throws Exception {
                        return value.getJSONObject("common").getString("mid");
                    }
                });

        // TODO 5 使用分组之后的状态判断是否为独立访客 下游输出转换为javaBean
        SingleOutputStreamOperator<TrafficPageViewBean> beanStream = keyedStream.map(new RichMapFunction<JSONObject, TrafficPageViewBean>() {
            ValueState<String> lastLoginDtState = null;

            @Override
            public void open(Configuration parameters) throws Exception {
                ValueStateDescriptor<String> stateDescriptor = new ValueStateDescriptor<>("last_login_dt", String.class);
                stateDescriptor.enableTimeToLive(StateTtlConfig.newBuilder(Time.days(1L)).build());
                lastLoginDtState = getRuntimeContext().getState(stateDescriptor);
            }

            @Override
            public TrafficPageViewBean map(JSONObject jsonObj) throws Exception {
                String lastLoginDt = lastLoginDtState.value();
                Long ts = jsonObj.getLong("ts");
                JSONObject page = jsonObj.getJSONObject("page");
                JSONObject common = jsonObj.getJSONObject("common");
                String curDt = DateFormatUtil.toDate(ts);
                String dorisCurDt = DateFormatUtil.toDorisDate(ts);
                Long uvCt = 0L;
                if (lastLoginDt == null || !lastLoginDt.equals(curDt)) {
                    // 当前为独立访客
                    uvCt = 1L;
                    lastLoginDtState.update(curDt);
                }
                Long svCt = 0L;
                if (StringUtils.isEmpty(page.getString("last_page_id"))) {
                    svCt = 1L;
                }

                return new TrafficPageViewBean("", "",
                        common.getString("vc"),
                        common.getString("ch"),
                        common.getString("ar"),
                        common.getString("is_new"),
//                        dorisCurDt,
                        "20231009",
                        uvCt,
                        svCt,
                        1L,
                        page.getLong("during_time"),
                        ts
                );
            }
        });

//        beanStream.print();

        // TODO 6 注册水位线
        SingleOutputStreamOperator<TrafficPageViewBean> withWaterMarkStream = beanStream.assignTimestampsAndWatermarks(WatermarkStrategy.<TrafficPageViewBean>forMonotonousTimestamps().withTimestampAssigner(new SerializableTimestampAssigner<TrafficPageViewBean>() {
            @Override
            public long extractTimestamp(TrafficPageViewBean element, long recordTimestamp) {
                return element.getTs();
            }
        }));

        // TODO 7 根据VcChArIsNew进行分组
        // TODO 8 开窗聚合
        SingleOutputStreamOperator<TrafficPageViewBean> reduceStream = withWaterMarkStream.keyBy(new KeySelector<TrafficPageViewBean, Tuple4<String, String, String, String>>() {
            @Override
            public Tuple4<String, String, String, String> getKey(TrafficPageViewBean value) throws Exception {
                return Tuple4.of(value.getVc(), value.getCh(), value.getAr(), value.getIsNew());
            }
        }).window(TumblingEventTimeWindows
                .of(org.apache.flink.streaming.api.windowing.time.Time.seconds(10L)))
                // 允许窗口迟到的时间
                .allowedLateness(org.apache.flink.streaming.api.windowing.time.Time.seconds(5L))
                .reduce(new ReduceFunction<TrafficPageViewBean>() {
                    @Override
                    public TrafficPageViewBean reduce(TrafficPageViewBean value1, TrafficPageViewBean value2) throws Exception {
                        value1.setUvCt(value1.getUvCt() + value2.getUvCt());
                        value1.setPvCt(value1.getPvCt() + value2.getPvCt());
                        value1.setSvCt(value1.getSvCt() + value2.getSvCt());
                        value1.setDurSum(value1.getDurSum() + value2.getDurSum());
                        return value1;
                    }
                }, new ProcessWindowFunction<TrafficPageViewBean, TrafficPageViewBean, Tuple4<String, String, String, String>, TimeWindow>() {
                    @Override
                    public void process(Tuple4<String, String, String, String> key, Context context, Iterable<TrafficPageViewBean> elements, Collector<TrafficPageViewBean> out) throws Exception {
                        TimeWindow window = context.window();
                        String stt = DateFormatUtil.toYmdHms(window.getStart());
                        String edt = DateFormatUtil.toYmdHms(window.getEnd());
                        for (TrafficPageViewBean element : elements) {
                            element.setStt(stt);
                            element.setEdt(edt);
                            out.collect(element);
                        }
                    }
                });

//        reduceStream.print();

        // TODO 9 写出到doris
        reduceStream.map(new MapFunction<TrafficPageViewBean, String>() {
            @Override
            public String map(TrafficPageViewBean value) throws Exception {
                SerializeConfig serializeConfig = new SerializeConfig();
                serializeConfig.setPropertyNamingStrategy(PropertyNamingStrategy.SnakeCase);
                return JSON.toJSONString(value,serializeConfig);
            }
        }).sinkTo(DorisUtil.getDorisSink("dws_traffic_vc_ch_ar_is_new_page_view_window"));

        // TODO 10 执行环境
        env.execute();
    }
}
